package com.yzg.simple.netty.protobuf.client;

import com.yzg.simple.netty.protobuf.MessageInfos;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.Random;

/**
 * @author misterWei
 * @create 2019年12月26号:23点14分
 * @mailbox mynameisweiyan@gmail.com
 *
 * 客户端Handler
 */
public class ClientHandler extends ChannelInboundHandlerAdapter{

    //当通道初始化成功的时候就会调用该方法
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        MessageInfos.MessageType messageType = null;
        int random = new Random().nextInt(3);
        if (random == 0){
            //用户
           messageType =  MessageInfos.MessageType.newBuilder().setDataType(MessageInfos.MessageType.DataType.UserType).setUser(MessageInfos.User.newBuilder().setId(50).setName("小红").build()).build();

        }else{
            //企业
            messageType =  MessageInfos.MessageType.newBuilder().setDataType(MessageInfos.MessageType.DataType.Company).setCompany(MessageInfos.Company.newBuilder().setFlag(true).setComName("BAT").build()).build();

        }

        ctx.writeAndFlush(messageType);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("接受来自客户端的信息:\r"+byteBuf.toString(CharsetUtil.UTF_8));
    }
    //异常处理器
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
